package graphql

import (
	"context"
	"errors"
	"happy-sudoku/graphql/graph"
	"happy-sudoku/internal/model"

	"github.com/99designs/gqlgen/graphql"
)

// requireAuth must be auth first
func requireAuth(ctx context.Context, obj interface{}, next graphql.Resolver) (res interface{}, err error) {
	auth := model.ForAuthContext(ctx)
	if auth == nil {
		return nil, errors.New("require auth")
	}

	if auth.GetError() != nil {
		return nil, auth.GetError()
	}

	return next(ctx)
}

func onlyMe(ctx context.Context, obj interface{}, next graphql.Resolver) (res interface{}, err error) {
	// logrus.Infof("%+v", obj)
	auth := model.ForAuthContext(ctx)
	if auth == nil {
		return nil, errors.New("onlyMe: Require Auth")
	}

	if auth.GetError() != nil {
		return nil, auth.GetError()
	}

	player, ok := obj.(*model.Player)
	if !ok {
		return nil, errors.New("onlyMe: Object is Not Player")
	}
	if player.ID != auth.PlayerID {
		return nil, errors.New("onlyMe: playerID not matched")
	}
	return next(ctx)
}

// Directives return directives map
func Directives() graph.DirectiveRoot {
	return graph.DirectiveRoot{
		RequireAuth: requireAuth,
		OnlyMe:      onlyMe,
	}
}
